package com.myjar.excel.util;


import org.joor.Reflect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Set;

public class TypeUtils {

    public static void getAllField(Class<?> clazz, Class<? extends Annotation> annotation, Set<Field> set) {
        assert notRootClass(clazz) && set != null;

        Field[] fields = clazz.getDeclaredFields();
        Arrays.stream(fields).filter(field -> field.isAnnotationPresent(annotation))
                .forEach(set::add);
        clazz = clazz.getSuperclass();
        if (notRootClass(clazz)) {
            getAllField(clazz, annotation, set);
        }
    }

    private static boolean notRootClass(Class<?> clazz) {
        return clazz != null && clazz != Object.class;
    }


    public static Object getFieldVal(Object target, Field field) {
        return Reflect.on(target)
                .field(field.getName()).get();
    }

    public static void setFieldVal(Object target, Field field, Object o) {
        Reflect.on(target)
                .set(field.getName(), o);
    }
}
